//
//  FilmViewController.m
//  MPFindPart
//
//  Created by xalo on 16/5/5.
//  Copyright © 2016年 马鹏. All rights reserved.
//

#import "FilmViewController.h"
#import <AFNetworking.h>
#import "PlayLinksModel.h"
#import "FilmModel.h"
#import "FilmCell.h"
#import "PlayViewController.h"

@interface FilmViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong,nonatomic)UISearchBar *searchBar;//搜索框
@property (strong,nonatomic)NSDictionary *parerter;//存放参数的字典
@property (strong,nonatomic)NSMutableArray *dataArray;//存放数据的数组
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation FilmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.titleView = self.searchBar;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    //注册xib
    [self.tableView registerNib:[UINib nibWithNibName:@"FilmCell" bundle:nil] forCellReuseIdentifier:@"FilmCell"];
  
}


//解析数据
- (void)pareserDataWithString:(NSString *)string{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    NSString *str1 = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet symbolCharacterSet]];
    NSLog(@"%@",str1);
    NSString *str= [NSString stringWithFormat:@"http://op.juhe.cn/onebox/movie/video?key=0327ee29d3c3588fb3f4f8140509cc4b&q=%@",str1];
    
        [manager GET:str
          parameters:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
             NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
              NSString *reason = dic[@"reason"];
              if ([reason isEqualToString:@"查询不到该影片相关信息"]) {
                  [self showAlertViewWithMessage:@"查不到该影片相关信息,请重新输入"];
                  
              }else{
                  
                   NSDictionary *resultDic = dic[@"result"];
                  FilmModel *model = [[FilmModel alloc] init];
                  [model setValuesForKeysWithDictionary:resultDic];
                  [self.dataArray addObject:model];
                  [self.tableView reloadData];
              }
             
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           
            NSLog(@"解析出错");
            
        }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark   tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FilmCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FilmCell" forIndexPath:indexPath];
    FilmModel *model = self.dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setCellWithModel:model];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FilmModel *model = self.dataArray[indexPath.row];
    CGRect descRect = [model.desc boundingRectWithSize:CGSizeMake(kWidth - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0] }context:nil];
    return descRect.size.height + 150 + 10 + 21 + 10 + 21 + 10 + 21 + 10 + 21 + 10 + 50 ;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PlayViewController *playVC = [[PlayViewController alloc] init];
    FilmModel *model = self.dataArray[indexPath.row];
    playVC.model = model.playLinkModel;
    UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:playVC];
    [self presentViewController:navC animated:YES completion:nil];
    
}

#pragma mark searchBar的代理方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    //回收键盘
    [searchBar resignFirstResponder];
    [self pareserDataWithString:searchBar.text];
    
}
//弹出警示框的方法
- (void)showAlertViewWithMessage:(NSString *)message{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (UISearchBar *)searchBar{
    
    if (!_searchBar) {
        
        _searchBar = [[UISearchBar alloc] initWithFrame:self.view.frame];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"请输入电影或者电视剧名称";
        
        
    }
    return _searchBar;
}
-(NSDictionary *)parerter{
    
    if (!_parerter) {
        
        _parerter = [NSDictionary dictionary];
        
    }
    return _parerter;
}
- (NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
@end
